package com.jinyou.chengfengshop.homeFragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinyou.chengfengshop.Constant.AppUrl;
import com.jinyou.chengfengshop.OkHttpUtils.CallBackUtil;
import com.jinyou.chengfengshop.OkHttpUtils.OkhttpUtil;
import com.jinyou.chengfengshop.R;
import com.jinyou.chengfengshop.activity.LoginActivity;
import com.jinyou.chengfengshop.adapter.HomeOrderAdapter;
import com.jinyou.chengfengshop.bean.orderNoBean;
import com.jinyou.chengfengshop.utils.CommonEvent;
import com.jinyou.chengfengshop.utils.CommonEventKey;
import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 *
 * 发单中
 * Created by zhuzhiqiang on 2018/9/27.
 */

public class orderUnTakefragment extends LazyLoadFragment {
    private View mView;
    private RecyclerViewPager order_rec;
    private HomeOrderAdapter mAdapter;
    private List<orderNoBean> odb;
    private LinearLayout no_order_im;

    private boolean isPrepared;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.home_fragment,null);
        }
        order_rec = (RecyclerViewPager) mView.findViewById(R.id.order_rec);
        LinearLayoutManager layout = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL,false);
        order_rec.setLayoutManager(layout);
        order_rec.setSinglePageFling(false);
        order_rec.setHasFixedSize(true);
        order_rec.addOnPageChangedListener(new RecyclerViewPager.OnPageChangedListener() {
            @Override
            public void OnPageChanged(int oldPosition, int newPosition) {
                if(odb!=null && odb.size()>0){

                    Gson gson = new Gson();
                    String obj2 = gson.toJson(odb.get(newPosition));

                    SharedPreferences sp = getActivity().getSharedPreferences("home_order",0);
                    SharedPreferences.Editor edt = sp.edit();
                    edt.putString("order",obj2);
                    edt.putString("type","d");
                    edt.commit();

                    EventBus.getDefault().post(new CommonEvent(CommonEventKey.HOME_ORDER_CHANGE));
                }
                Log.d("orderUnDoneBfragment", "oldPosition:" + oldPosition + " newPosition:" + newPosition);
            }
        });

        order_rec.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {


            }
        });

        isPrepared = true;
        no_order_im =(LinearLayout) mView.findViewById(R.id.no_order_im);
        lazyLoad();
        return mView;
    }



    //获取未完成订单列表---发单中
    private void getUnTakeOrder(){
        HashMap<String,String> paramsMap = new HashMap<>();
        SharedPreferences sh = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        String tocken = sh.getString("tocken","");
        paramsMap.put("token",tocken);
        paramsMap.put("sysCustomer","o2o-chengfeng");
        OkhttpUtil.okHttpPost(AppUrl.ORDER_LIST_UNTAKE, paramsMap, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                Toast.makeText(getActivity(),"失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {//请求成功时调用，执行在UI线程
                try {
                    JSONObject obj = new JSONObject(response);
                    int code = obj.getInt("status");


                    if(code == 1){
                        if(null != odb){
                            odb.clear();
                            //mAdapter.notifyDataSetChanged();
                        }
                        int total = obj.getInt("size");//已完成数量

                        String ob = obj.getString("data");

                        if (ob != null && !ob.equals("")) {
                            Type typeOfT = new TypeToken<List<orderNoBean>>() {
                            }.getType();
                            odb = new Gson().fromJson(ob, typeOfT);

                        }

                        if(odb.size()>0){
                            order_rec.setVisibility(View.VISIBLE);
                            no_order_im.setVisibility(View.INVISIBLE);

                            mAdapter = new HomeOrderAdapter(4,odb,getActivity());
                            order_rec.setAdapter(mAdapter);

                            Gson gson = new Gson();
                            String obj2 = gson.toJson(odb.get(0));
                            //初始化首页第一个订单信息
                            SharedPreferences sp = getActivity().getSharedPreferences("home_order",0);
                            SharedPreferences.Editor edt = sp.edit();
                            edt.putString("order",obj2);
                            edt.putString("type","d");
                            edt.commit();

                            EventBus.getDefault().post(new CommonEvent(CommonEventKey.HOME_ORDER_CHANGE));
                        }else {
                            order_rec.setVisibility(View.INVISIBLE);
                            no_order_im.setVisibility(View.VISIBLE);
                        }


                    }else {

                        Toast.makeText(getActivity(),obj.getString("error"),Toast.LENGTH_SHORT).show();
                        if(obj.getString("type").equals("notLogin")){
                            reLogin();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }




    //重新登陆
    private void reLogin(){
        SharedPreferences sh = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor edt = sh.edit();
        edt.putString("tocken","");
        edt.putString("info","");
        edt.commit();
        Intent mIntent = new Intent(getActivity(),LoginActivity.class);
        startActivity(mIntent);
        getActivity().finish();
    }

    @Override
    protected void lazyLoad() {
        if(!isPrepared || !isVisible) {
            return;
        }
        getUnTakeOrder();
    }
}
